﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao.PlcDao;
using DeHeng_Mes.Model.BossModel;
using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.Singleton;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using S7.Net;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.ServiceModel.Channels;
using System.Windows.Documents;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace DeHeng_Mes.Service.Plc
{
    #region 数据读取线程
    #endregion

    /// <summary>
    /// 下发工厂订单给Plc
    /// </summary>
    public class LineMesToPlc
    {

        #region 成员实例
        #endregion

        /// <summary>
        /// 下发工单至Plc通用方法
        /// </summary>
        /// <param name="orderPlan"></param>
        /// <returns></returns>
        public (string, string) OrderToPlc(OrderPlan orderPlan)
        {
            if (PlcConnectionManager.plcContainer != null && PlcConnectionManager.plcContainer.Count > 0)
            {
                try
                {
                    // 获取该物料对应的PlcName
                    string plcName = string.Join(",",MappingTable.GetPlcNameByMaterial(orderPlan.material_id));

                    string message = $"工单配置成功，工单号为[{orderPlan.wo_code}]，数量为[{orderPlan.plan_num}]，物料名称为[{orderPlan.material_name}]，已存在{OrderSingleton.GetCount()}个工单";

                    OrderSingleton.AddOrder(new OrderSingletonModel()
                    {
                        LineName = orderPlan.eqpt_id,
                        MaterialId = orderPlan.material_id,
                        MaterialName = orderPlan.material_name,
                        OrderId = orderPlan.wo_code,
                        ProducessNum = orderPlan.plan_num,
                        PlcName = plcName
                    });

                    Tools.ProduceLogText(message);

                    return ("1", message);
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"工单下发失败：原因是{ex.Message}");

                    OrderClear(orderPlan.wo_code);

                    // 失败响应
                    return ("0", "工单下发失败：内部错误");
                }
            }

            Tools.ProduceLogTextError($"工单下发失败：原因是PLC实例未配置");

            // 失败响应
            return ("0", "工单下发失败：内部错误");
        }

        /// <summary>
        /// 清除工单
        /// </summary>
        /// <param name="material_id"></param>
        public void OrderClear(string wo_code)
        {
            // 删除匹配的数据
            OrderSingleton.RemoveByOrderId(wo_code);
        }
    }

}
